package com.kongwg.exer;

import org.junit.Test;

/**
 * @author kongwg
 * @create 2020-12-08 9:48
 */
public class StringDemo {


    /**
     * 将一个字符串进行反转。将字符串中指定部分进行反转。
     * 比如“abcdefg”反转为”abfedcg”
     */
    //方式1
    public String reverse(String str,int startIndex,int endIndex){

        char[] arr = str.toCharArray();
        for (int x = startIndex, y  = endIndex;x < y;x++,y--){
            char temp = arr[x];
            arr[x] = arr[y];
            arr[y] = temp;
        }

        return new String(arr);
    }
    //方式二
    public String reverse1(String str,int startIndex,int endIndex){
        if (str != null){
            String reverseStr = str.substring(0,startIndex);
            for (int i = endIndex; i >= startIndex ; i--) {
                reverseStr += str.charAt(i);
            }
            reverseStr += str.substring(endIndex+1);
            return reverseStr;
        }
        return null;
    }
    //方式三
    public String reverse2(String str,int startIndex,int endIndex){
        StringBuilder builder = new StringBuilder(str.length());
        builder.append(str.substring(0,startIndex));
        for (int i = endIndex ; i >= startIndex;i--){
            builder.append(str.charAt(i));

        }
        builder.append(str.substring(endIndex+1));
        return new String(builder);
    }
    @Test
    public void test1(){
       StringDemo s1 = new StringDemo();
       String st= "abcdefg";
        String reverse = s1.reverse(st, 2, 5);
        System.out.println(reverse);

        String reverse1 = s1.reverse1(st, 2, 5);
        System.out.println(reverse1);
        String reverse3 = s1.reverse2(st, 2, 5);
        System.out.println(reverse3);

    }
}
